import React, { useEffect, useState } from 'react';
import { Button, Space, Tag, Switch, Popconfirm, Typography, message, Tooltip, Badge, Descriptions } from 'antd';
import { DeleteOutlined, ReloadOutlined, ClockCircleOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { TableCard } from '@/components/common';
import { judgeServerService } from '@/services/judgeServerService';
import { JudgeServer, JudgeServerStatus } from '@/types/judgeServer';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

// 扩展dayjs以支持相对时间
dayjs.extend(relativeTime);

const { Title, Text } = Typography;

const JudgeServerPage: React.FC = () => {
  const [servers, setServers] = useState<JudgeServer[]>([]);
  const [token, setToken] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [refreshing, setRefreshing] = useState<boolean>(false);

  // 获取评测服务器列表
  const fetchJudgeServers = async () => {
    try {
      setLoading(true);
      const res = await judgeServerService.getJudgeServers();
      setServers(res.data.servers);
      setToken(res.data.token);
      setLoading(false);
    } catch (error) {
      console.error('Failed to fetch judge servers:', error);
      message.error('获取评测服务器列表失败');
      setLoading(false);
    }
  };

  // 刷新评测服务器列表
  const handleRefresh = async () => {
    setRefreshing(true);
    await fetchJudgeServers();
    setRefreshing(false);
  };

  // 更新评测服务器状态
  const toggleServerStatus = async (server: JudgeServer) => {
    try {
      await judgeServerService.updateJudgeServer(server.id, {
        is_disabled: !server.is_disabled
      });
      message.success(`${server.is_disabled ? '启用' : '禁用'}服务器成功`);
      // 更新本地状态
      setServers(servers.map(s => 
        s.id === server.id ? { ...s, is_disabled: !s.is_disabled } : s
      ));
    } catch (error) {
      console.error('Failed to update judge server:', error);
      message.error(`${server.is_disabled ? '启用' : '禁用'}服务器失败`);
    }
  };

  // 删除评测服务器
  const handleDelete = async (id: number) => {
    try {
      await judgeServerService.deleteJudgeServer(id);
      message.success('删除服务器成功');
      // 更新本地状态
      setServers(servers.filter(s => s.id !== id));
    } catch (error) {
      console.error('Failed to delete judge server:', error);
      message.error('删除服务器失败');
    }
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case JudgeServerStatus.NORMAL:
        return <Tag color="success">正常</Tag>;
      case JudgeServerStatus.ERROR:
        return <Tag color="error">错误</Tag>;
      case JudgeServerStatus.WARNING:
        return <Tag color="warning">警告</Tag>;
      default:
        return <Tag color="default">{status}</Tag>;
    }
  };

  // 获取心跳时间显示
  const getHeartbeatDisplay = (lastHeartbeat: string) => {
    const heartbeatTime = dayjs(lastHeartbeat);
    const now = dayjs();
    const diff = now.diff(heartbeatTime, 'minute');
    
    let color = 'success';
    if (diff > 10) {
      color = 'error';
    } else if (diff > 5) {
      color = 'warning';
    }
    
    return (
      <Space>
        <Badge status={color as 'success' | 'warning' | 'error'} />
        <Tooltip title={heartbeatTime.format('YYYY-MM-DD HH:mm:ss')}>
          <Text>{heartbeatTime.fromNow()}</Text>
        </Tooltip>
      </Space>
    );
  };

  // 获取扩展行内容
  const getExpandedContent = (record: JudgeServer) => {
    return (
      <Descriptions column={2} bordered size="small">
        <Descriptions.Item label="评测器版本">
          {record.judger_version}
        </Descriptions.Item>
        <Descriptions.Item label="CPU核心数">
          {record.cpu_core}
        </Descriptions.Item>
        <Descriptions.Item label="内存使用率">
          {record.memory_usage}%
        </Descriptions.Item>
        <Descriptions.Item label="CPU使用率">
          {record.cpu_usage}%
        </Descriptions.Item>
        <Descriptions.Item label="创建时间">
          {dayjs(record.create_time).format('YYYY-MM-DD HH:mm:ss')}
        </Descriptions.Item>
        <Descriptions.Item label="当前任务数">
          {record.task_number}
        </Descriptions.Item>
        <Descriptions.Item label="服务地址" span={2}>
          {record.service_url}
        </Descriptions.Item>
      </Descriptions>
    );
  };

  useEffect(() => {
    fetchJudgeServers();
  }, []);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '主机名',
      dataIndex: 'hostname',
      key: 'hostname',
    },
    {
      title: 'IP 地址',
      dataIndex: 'ip',
      key: 'ip',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '最后心跳',
      dataIndex: 'last_heartbeat',
      key: 'last_heartbeat',
      render: (heartbeat: string) => getHeartbeatDisplay(heartbeat),
    },
    {
      title: '可用状态',
      dataIndex: 'is_disabled',
      key: 'is_disabled',
      render: (disabled: boolean, record: JudgeServer) => (
        <Switch
          checked={!disabled}
          onChange={() => toggleServerStatus(record)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: JudgeServer) => (
        <Popconfirm
          title="确定要删除此评测服务器吗？"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <Button 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
          >
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];

  return (
    <div>
      {token && (
        <div style={{ marginBottom: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
          <Space align="center">
            <ClockCircleOutlined />
            <Text strong>评测服务器令牌:</Text>
            <Text copyable ellipsis style={{ maxWidth: '300px' }}>
              {token}
            </Text>
            <Text type="secondary">(新服务器接入时需要此令牌)</Text>
          </Space>
        </div>
      )}
      
      <TableCard
        title="评测服务器管理"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<ReloadOutlined />}
              loading={refreshing}
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </Space>
        }
        tableProps={{
          dataSource: servers,
          columns: columns,
          rowKey: 'id',
          loading: loading,
          pagination: false,
          expandable: {
            expandedRowRender: getExpandedContent,
            expandIcon: ({ expanded, onExpand, record }: any) => (
              <Button
                type="text"
                icon={<InfoCircleOutlined />}
                onClick={(e) => onExpand(record, e)}
                style={{ color: expanded ? '#1890ff' : undefined }}
              />
            ),
            rowExpandable: () => true,
          },
        }}
      />
    </div>
  );
};

export default JudgeServerPage; 